package cn.wolfcode.service.impl;


import cn.wolfcode.domain.Employee;
import cn.wolfcode.mapper.EmployeeMapper;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IEmployeeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
@Service
@Transactional
public class EmployeeServiceImpl implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public void delete(Long id) {
//        System.out.println(1/0);  // 定义异常
        employeeMapper.deleteByPrimaryKey(id);
    }

    // ======= 员工表新增 + 员工_角色表 新增 ========
    @Override
    public void insert(Employee employee, Long[] roleIds) {
        // 员工表新增
        employeeMapper.insert(employee);
        // 员工_角色表
        if (roleIds != null && roleIds.length > 0) {
            for (Long roleId : roleIds) {
                employeeMapper.insertRelation(employee.getId(), roleId);
            }
        }
    }

    @Override
    public Employee selectOne(Long id) {
        Employee employee = employeeMapper.selectByPrimaryKey(id);
        return employee;
    }

    @Override
    public List<Employee> selectAll() {

        List<Employee> employees = employeeMapper.selectAll();
        return employees;
    }

    // =========== 编辑  ===========
    @Override
    public void update(Employee employee, Long[] roleIds) {
        // 员工表的 修改
        employeeMapper.updateByPrimaryKey(employee);
        // 先删除 员工_角色表 数据
        employeeMapper.deleteRelation(employee.getId());
        // 再新增 员工_角色表 数据
        if (roleIds != null && roleIds.length > 0) {
            for (Long roleId : roleIds) {
                employeeMapper.insertRelation(employee.getId(), roleId);
            }
        }

    }

    @Override
    public PageInfo<Employee> query(QueryObject qo) {
        // 使用后端分页插件
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        List<Employee> employees = employeeMapper.selectForList(qo);
        return new PageInfo<>(employees);

        // 日志
/*        log.info("=======info信息======");
        int count = employeeMapper.selectForCount(qo);
        if (count == 0) {
            return new PageResult<>(qo.getCurrentPage(), qo.getPageSize(), 0, Collections.emptyList());
        }
        return new PageResult<>(qo.getCurrentPage(), qo.getPageSize(), count, employeeMapper.selectForList(qo));
        */
    }

    @Override
    public Employee login(String username, String password) {
        return employeeMapper.selectByUsernameAndPassword(username, password);
    }
}
